package com.breadenglish.cms.api.app.sys.manager;

import com.breadenglish.cms.api.app.common.anotation.EnablePaging;
import com.breadenglish.cms.api.app.common.context.PagingContextHolder;
import com.breadenglish.cms.api.app.common.page.Page;
import com.breadenglish.cms.api.app.common.page.QueryPage;
import com.breadenglish.cms.api.app.common.utils.PropertyConfigurerUtils;
import com.breadenglish.cms.api.app.dao.AudioDao;
import com.breadenglish.cms.api.app.domain.constants.Constants;
import com.breadenglish.cms.api.app.domain.db.Audio;
import com.breadenglish.cms.api.app.domain.model.ResultMessage;
import com.breadenglish.cms.api.app.domain.query.AudioQuery;
import com.breadenglish.cms.api.app.sys.service.VideoService;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.mp3.MP3AudioHeader;
import org.jaudiotagger.audio.mp3.MP3File;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lixuegang on 2015/12/28.
 */
@Controller
@RequestMapping("/likeVideo")
public class VideoLikeConroller {

    private static final Logger logger = LoggerFactory.getLogger(VideoLikeConroller.class);

    public static String filePath = PropertyConfigurerUtils.getProperty(Constants.FILE_PATH);

    @Resource
    private AudioDao audioDao;

    @Resource
    private VideoService videoService;

    /**
     * who be like主页面
     *
     * @param
     * @return query_like_video
     */
    @RequestMapping(value = "/forwardQueryLike.html")
    public String forwardQueryLike() throws Throwable {
        return "app/who_be_like/query_like_video";
    }


    /**
     * 显示字典信息页面
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/displayAudioTemplate.html")
    public ModelAndView displayAudioTemplate(@RequestParam("audioId") String audioId) throws Throwable {
        ModelAndView mav = new ModelAndView();
        mav.addObject("audioInfo", videoService.queryAudioById(Long.valueOf(audioId)));
        mav.setViewName("app/who_be_like/display_like_video");
        return mav;
    }

    /**
     * 跳转到添加WhoBeLike
     *
     * @return insert_like_video
     * @throws Throwable
     */
    @RequestMapping(value = "/insertLikeTemplate.html")
    public String insertLikeTemplate() throws Throwable {
        return "app/who_be_like/insert_like_video";
    }

    /**
     * 查询所有Video
     *
     * @param queryPage
     * @param audio
     * @return Map
     */
    @EnablePaging
    @RequestMapping(value = "/queryLikeVideo.html")
    @ResponseBody
    public Map<String, Object> queryVideo(@ModelAttribute("queryPage") QueryPage queryPage, @ModelAttribute("audio") Audio audio) {
        List<AudioQuery> audios = audioDao.queryAudio(audio);
        // 获取翻页参数
        Page page = PagingContextHolder.getPage();
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("total", page.getTotalResult());
        resultMap.put("rows", audios);
        return resultMap;
    }

    /**
     * 增加WhoBeLike
     *
     * @param audio
     * @return ResultData
     */
    @RequestMapping(value = "/insertLikeVideo.html")
    @ResponseBody
    public ResultMessage insertVideo(@ModelAttribute("audio") Audio audio, HttpServletRequest request) throws Throwable {
        String savePath = filePath;
        if (filePath.equals("/upload")) {
            savePath = request.getRealPath(filePath);
        }
        File f1 = new File(savePath);
        if (!f1.exists()) {
            f1.mkdirs();
        }
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
        savePath = savePath + File.separator + formater.format(new Date());
        /*ResultData resultData = new ResultData();
        audio.setDeliveryTime(new Date());
        audio.setCreateTime(new Date());
        int result = audioDao.insert(audio);
        if (result == 0) {
            resultData.setResultMessage("插入失败~");
            return resultData;
        }
        resultData.setResultMessage("插入成功");*/
        videoService.insertVideo(audio, savePath);
        /*ResultMessage message = new ResultMessage();
        message.setTitle(PropertyConfigurerUtils.getProperty(MessageConstants.MESSAGE_SUCCESS_TITLE));
        message.setSuccess(true);
        message.getContent().add("添加音频成功");*/
        return CommonUtils.createResultMessageStr("添加音频成功");
    }

    /**
     * 更新 Video
     *
     * @param audio
     * @return ResultData
     */
    @RequestMapping(value = "/updateLikeVideo.html")
    @ResponseBody
    public ResultMessage updateVideo(@ModelAttribute("audio") Audio audio, HttpServletRequest request) throws Throwable {
        String savePath = filePath;
        if (filePath.equals("/upload")) {
            savePath = request.getRealPath(filePath);
        }
        File f1 = new File(savePath);
        if (!f1.exists()) {
            f1.mkdirs();
        }
        SimpleDateFormat formater = new SimpleDateFormat("yyyyMMdd");
        savePath = savePath + File.separator + formater.format(new Date());
        videoService.updateVideo(audio, savePath);



        /*ResultMessage message = new ResultMessage();
        message.setTitle(PropertyConfigurerUtils.getProperty(MessageConstants.MESSAGE_SUCCESS_TITLE));
        message.setSuccess(true);
        message.getContent().add("更新音频成功");*/

        /*ResultData resultData = new ResultData();
        int result = audioDao.update(audio);
        if (result == 0) {
            resultData.setResultMessage("更新失败");
        }
        resultData.setResultMessage("更新成功");*/
        return CommonUtils.createResultMessageStr("更新音频成功");
    }


    /**
     * 删除Audio
     *
     * @param audioIds
     * @return ResultData
     */
    @RequestMapping(value = "/deleteLikeVideo.html")
    @ResponseBody
    public ResultMessage deleteVideo(@RequestParam("audioIds") String audioIds) throws Throwable{
        videoService.deleteVideo(audioIds);
        /*ResultData resultData = new ResultData();
        int result = audioDao.deleteByPrimaryKey(Long.valueOf(audioIds));
        if (result == 0) {
            resultData.setResultMessage("删除失败");
            return resultData;
        }
        resultData.setResultMessage("删除成功");*/
        return CommonUtils.createResultMessageStr("删除音频成功!");
    }

    /**
     * 跳转到更新页面
     *
     * @param audioId
     * @return ModelAndView
     */
    @RequestMapping(value = "/forwardUpdateVideo.html")
    public ModelAndView forwardUpdateVideo(@RequestParam("audioId") String audioId) throws Throwable {
        ModelAndView mav = new ModelAndView();
        mav.addObject("audioInfo", videoService.queryAudioById(Long.valueOf(audioId)));
        mav.setViewName("app/who_be_like/edit_like_video");
        return mav;
    }

    /**
     * 解析音频时常
     *
     * @return
     * @throws Throwable
     */
    @RequestMapping(value = "/analysisTime.html", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> analysisTime(@RequestParam("fileUrl") String fileUrl) throws Throwable {
        Map<String, String> result = new HashMap<String, String>();
        int time = 0;
        try {
            MP3File f = (MP3File) AudioFileIO.read(new File(fileUrl));
            MP3AudioHeader audioHeader = (MP3AudioHeader) f.getAudioHeader();
            time = audioHeader.getTrackLength();
        } catch (Exception e) {
        }
        long hour = time / 3600;    //小时
        long minute = time % 3600 / 60;  //分钟
        long second = time % 60;        //秒
        String timeStr = "";
        if (hour != 0) {
            timeStr += hour + "时";
        }
        if (minute != 0) {
            timeStr += minute + "分";
        }
        if (second != 0) {
            timeStr += second + "秒";
        }
        result.put("time", timeStr + " (" + time + "s)");
        return result;
    }

}
















